package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SimpleStatementHandler
 * @Description TODO
 * @Auth ying.xiao
 * @Date 2021/1/29
 * @Version 1.0.0
 */
public class SimpleStatementHandler extends BaseStatementHandler {

    public SimpleStatementHandler(Configuration configuration, MappedStatement mappedStatement, Object[] params) {
        super(configuration, mappedStatement,params);
    }

    @Override
    public <E> List<E> query(PreparedStatement statement) throws Exception {
        // 5. 执行sql
        ResultSet resultSet = statement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        ArrayList<Object> objects = new ArrayList<>();

        // 6. 封装返回结果集
        while (resultSet.next()){
            Object o =resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {

                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);


            }
            objects.add(o);

        }
        return (List<E>) objects;
    }

    @Override
    public int update(PreparedStatement preparedStatement) throws Exception {
        preparedStatement.execute();
        int i = preparedStatement.getUpdateCount();
        return i;
    }


}
